import math

def normalize(v):
    lenv = math.sqrt(v.x**2 + v.y**2)
    v.x /= lenv
    v.y /= lenv
    return v.x,v.y

def dot_product(a,b):
    d_p = a.x*b.x + a.y*b.y
    return d_p

def projection(a,b):
    proj_x = ( dot_product(a,b) / (b.x**2 + b.y**2) ) * b.x
    proj_y = ( dot_product(a,b) / (b.x**2 + b.y**2) ) * b.y
    return proj_x,proj_y
    
def perproduct(v):
    rn_x = -a.y
    rn_y = a.x
    
    ln_x = a.y
    ln_y = -a.x
    return rn_x,rn_y, ln_x,ln_y

def get_angle(x,y):
    return math.atan2(x,y)
    
def get_xy(a,d):
    x=math.sin(a)*-d
    y=math.cos(a)*-d
    return x,y
    
def get_dist(x,y):
    dist = math.sqrt(x**2 + y**2)
    return dist      
      
def buildpoints(box):
    points = []
    points.append((box.x - box.xw, box.y - box.yw))
    points.append((box.x + box.xw, box.y - box.yw))
    points.append((box.x + box.xw, box.y + box.yw))
    points.append((box.x - box.xw, box.y + box.yw))
    return points
    
def alignpoints(poly):
    xavg = 0
    yavg = 0
    for n in range(0,len(poly.points)):
        xavg += poly.points[n][0]
        yavg += poly.points[n][1]
    xavg /= len(poly.points)
    yavg /= len(poly.points)
    
    for n in range(0,len(poly.points)):
        poly.points[n] = (poly.points[n][0] + poly.x - xavg, poly.points[n][1] + poly.y - yavg)
        
def buildangles(points):
    angles = []
    for n in range(0,len(points)):
        try: angles.append(get_angle(points[n+1][0] - points[n][0],points[n+1][1] - points[n][1]))
        except IndexError: angles.append(get_angle(points[0][0] - points[n][0],points[0][1] - points[n][1]))
    return angles

    